package com.itheima.exception;

import com.itheima.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author: Zheng
 * @date: 2022/8/25 22:47
 * @description:
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e){
        e.printStackTrace();

        String msg = e.getMessage();

        if (msg.contains("Duplicate entry")){
            String value = msg.split(" ")[2];

            return R.error(value+", 已存在！");
        }
        return R.error("未知错误！");
    }

    @ExceptionHandler(CustomException.class)
    public R handleCustomException(CustomException e){
        e.printStackTrace();
        return R.error(e.getMessage());
    }
}
